package cn.tedu.boot23.controller;

import cn.tedu.boot23.entity.Emp;
import cn.tedu.boot23.utils.DBUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.sql.*;
import java.util.ArrayList;

@RestController
public class EmpController {
    @RequestMapping("/insert")
    public String insert(Emp emp){
        System.out.println("emp="+emp);
        try(Connection conn= DBUtils.getConn()) {
            String sql="insert into myemp values(null,?,?,?)";
            PreparedStatement ps=conn.prepareStatement(sql);
            ps.setString(1,emp.getName());
            ps.setInt(2,emp.getSal());
            ps.setString(3,emp.getJob());
            ps.executeUpdate();
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return"添加成功!<a href='/'>返回首页</a>";
    }
    @RequestMapping("/select")
    public String select(){
        ArrayList<Emp> list=new ArrayList<>();
        try (Connection conn=DBUtils.getConn()){
            String sql="select * from myemp";
            Statement s=conn.createStatement();
            ResultSet rs=s.executeQuery(sql);
            while (rs.next()){
                int id=rs.getInt(1);
                String name=rs.getString(2);
                int sal=rs.getInt(3);
                String job=rs.getString(4);
                Emp e=new Emp(id,name,sal,job);
                list.add(e);
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }
        String html = "<table border=1>";
        html+="<caption>员工列表</caption>";
        html+="<tr><th>id</th><th>名字</th><th>工资</th><th>工作</th></tr>";
        //遍历集合
        for (Emp e:list) {
            html+="<tr>";
            html+="<td>"+e.getId()+"</td>";
            html+="<td>"+e.getName()+"</td>";
            html+="<td>"+e.getSal()+"</td>";
            html+="<td>"+e.getJob()+"</td>";
            html+="</tr>";
        }
        html+="</table>";
        return html;
    }
}
